package com.woniuxy.yoga.product.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.yoga.business.dao.model.BusinessStore;
import com.woniuxy.yoga.commons.core.model.PageInfo;
import com.woniuxy.yoga.commons.core.model.Result;
import com.woniuxy.yoga.commons.core.statedata.BusinessState;
import com.woniuxy.yoga.commons.core.statedata.ProductState;
import com.woniuxy.yoga.product.client.BusinessStoreClient;
import com.woniuxy.yoga.product.client.dto.business.BusinessStoreDTO;
import com.woniuxy.yoga.product.dao.mapper.ProductTypeMapper;
import com.woniuxy.yoga.product.dao.model.Product;
import com.woniuxy.yoga.product.dao.mapper.ProductMapper;
import com.woniuxy.yoga.product.dao.model.ProductType;
import com.woniuxy.yoga.product.model.dto.AllProductDTO;
import com.woniuxy.yoga.product.model.dto.ProductDTO;
import com.woniuxy.yoga.product.model.exception.ProductException;
import com.woniuxy.yoga.product.model.exception.ProductExceptionCode;
import com.woniuxy.yoga.product.model.param.AddProductParam;
import com.woniuxy.yoga.product.model.param.QueryProductParam;
import com.woniuxy.yoga.product.service.service.ProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 产品表 服务实现类
 * </p>
 *
 * @author 韦用文,刘存益,郎腾霄
 * @since 2023年11月28日
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductTypeMapper productTypeMapper;

    @Autowired
    private BusinessStoreClient businessStoreClient;

    /**
     * 用户查询可用产品
     * @return
     */
    @Override
    public List<ProductDTO> queryNormalProduct() {
        //准备查询条件
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        //上架的产品
        wrapper.eq("product_state", ProductState.PRODUCT_STATE_NORMAL);
        List<Product> products = productMapper.selectList(wrapper);
        //集合转换
        List<ProductDTO> productDTOS = new ArrayList<>();
        if (products!=null&&products.size()>0){
            for (Product product : products) {
                //对象转换
                ProductDTO productDTO = BeanUtil.toBean(product, ProductDTO.class);
                //给门店名称赋值
                Result<BusinessStoreDTO> businessStoreDTOResult = businessStoreClient.selByBusinessStoreId(product.getStoreId());
                if (businessStoreDTOResult.getCode()!=200) throw new ProductException(businessStoreDTOResult.getCode(),businessStoreDTOResult.getMessage());
                BusinessStoreDTO businessStoreDTO = businessStoreDTOResult.getData();
                productDTO.setStoreName(businessStoreDTO.getStoreName());
                //保存到集合中
                productDTOS.add(productDTO);
            }
        }
        return productDTOS;
    }

    /**
     * 新增产品
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addProduct(AddProductParam param) {
        ProductType productType = productTypeMapper.selectById(param.getProductTypeId());
        //判断产品类型是否存在
        if (productType==null) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_TYPE_NOT_EXIST);
        //判断产品类型状态是否异常
        if (productType.getProductTypeState()!=ProductState.PRODUCT_TYPE_STATE_NORMAL) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_TYPE_STATE_ERROR);
        //判断是否报错
        Result<BusinessStoreDTO> businessStoreResult = businessStoreClient.selByBusinessStoreId(param.getStoreId());
        if (businessStoreResult.getCode()!=200) throw new ProductException(businessStoreResult.getCode(),businessStoreResult.getMessage());
        //获取数据
        BusinessStoreDTO businessStore = businessStoreResult.getData();
        //判断是否存在该场馆
        if (businessStore==null) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_STORE_ABSENT);
        //判断场馆状态是否异常
        if (businessStore.getStoreState()==BusinessState.STORE_STATE_DELETE) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_STORE_STATE_ERROR);
        //判断产品名是否重复
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("product_name",param.getProductName());
        //索引排序
        wrapper.orderByAsc("product_id");
        Product product = productMapper.selectOne(wrapper);
        if (product!=null) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_EXIST);
        //对象转换
        Product data = BeanUtil.toBean(param, Product.class);
        //产品类型赋值
        data.setProductTypeName(productType.getProductTypeName());
        //状态赋值 初始值为下架
        data.setProductState(ProductState.PRODUCT_TYPE_STATE_DISABLE);
        productMapper.insert(data);
    }

    /**
     * 上架产品
     * @param productId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void normalProduct(Integer productId) {
        //查询产品
        Product product = productMapper.selectById(productId);
        //判断是否存在该产品
        if (product==null) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_NOT_EXIST);
        //判断当前产品是否是下架状态
        if (product.getProductState()!=ProductState.PRODUCT_STATE_DISABLE) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_STATE_ERROR);
        //查询该产品的产品类型
        ProductType productType = productTypeMapper.selectById(product.getProductTypeId());
        //判断产品的产品类型是否存在
        if (productType==null) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_TYPE_NOT_EXIST);
        //判断产品的产品类型状态是否异常
        if (productType.getProductTypeState()!=ProductState.PRODUCT_TYPE_STATE_NORMAL) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_TYPE_STATE_ERROR);
        //修改产品状态
        product.setProductState(ProductState.PRODUCT_STATE_NORMAL);
        productMapper.updateById(product);
    }

    /**
     * 下架产品
     * @param productId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void disableProduct(Integer productId) {
        //查询产品
        Product product = productMapper.selectById(productId);
        //判断是否存在该产品
        if (product==null) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_NOT_EXIST);
        //判断产品状态是否是上架
        if (product.getProductState()!=ProductState.PRODUCT_STATE_NORMAL) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_STATE_ERROR);
        //查询产品的产品类型
        ProductType productType = productTypeMapper.selectById(product.getProductTypeId());
        //判断产品类型是否存在
        if (productType==null) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_TYPE_NOT_EXIST);
        //判断产品类型状态是否异常
        if (productType.getProductTypeState()!=ProductState.PRODUCT_TYPE_STATE_NORMAL) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_TYPE_STATE_ERROR);
        //修改产品状态
        product.setProductState(ProductState.PRODUCT_STATE_DISABLE);
        productMapper.updateById(product);
    }

    /**
     * 删除产品
     * @param productId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProduct(Integer productId) {
        //查询产品
        Product product = productMapper.selectById(productId);
        //判断产品是否存在
        if (product==null) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_NOT_EXIST);
        //判断产品状态是否异常
        if (product.getProductState()==ProductState.PRODUCT_STATE_DELETE) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_STATE_ERROR);
        //查询产品的产品类型
        ProductType productType = productTypeMapper.selectById(product.getProductTypeId());
        //判断产品类型是否存在
        if (productType==null) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_TYPE_NOT_EXIST);
        //判断产品类型状态是否异常
        if (productType.getProductTypeState()!=ProductState.PRODUCT_TYPE_STATE_NORMAL) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_TYPE_STATE_ERROR);
        //修改产品状态
        product.setProductState(ProductState.PRODUCT_STATE_DELETE);
        productMapper.updateById(product);
    }

    /**
     * 商家查询自己的所有产品
     * @param param
     * @return
     */
    @Override
    public PageInfo queryProduct(QueryProductParam param) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        //当前商家的所有产品
        wrapper.eq("store_id",param.getStoreId());
        //产品名搜索
        if (ObjectUtil.isNotEmpty(param.getProductName())){
            wrapper.like("product_name",param.getProductName());
        }
        //最低产品价格搜索
        if (ObjectUtil.isNotEmpty(param.getProductPriceMin())){
            wrapper.ge("product_price",param.getProductPriceMin());
        }
        //最高产品价格搜索
        if (ObjectUtil.isNotEmpty(param.getProductPriceMax())){
            wrapper.le("product_price",param.getProductPriceMax());
        }
        //产品类型ID搜索
        if (ObjectUtil.isNotEmpty(param.getProductTypeId())){
            wrapper.eq("product_type_id",param.getProductTypeId());
        }
        //产品状态搜索
        if (ObjectUtil.isNotEmpty(param.getProductState())){
            wrapper.eq("product_state",param.getProductState());
        }
        //索引排序
        wrapper.orderByAsc("product_id");
        //分页查询
        Page<Product> page = new Page<>(param.getPageNum()==null?1:param.getPageNum(),param.getPageSize()==null?5:param.getPageSize());
        productMapper.selectPage(page,wrapper);
        //集合转换
        List<AllProductDTO> allProductDTOS = new ArrayList<>();
        if (page.getRecords()!=null&&page.getRecords().size()>0){
            for (Product product : page.getRecords()) {
                //对象转换
                AllProductDTO allProductDTO = BeanUtil.toBean(product, AllProductDTO.class);
                //门店名称赋值
                Result<BusinessStoreDTO> businessStoreResult = businessStoreClient.selByBusinessStoreId(product.getStoreId());
                //判断是否报错
                if (businessStoreResult.getCode()!=200) throw new ProductException(businessStoreResult.getCode(),businessStoreResult.getMessage());
                //获取数据
                BusinessStoreDTO businessStore = businessStoreResult.getData();
                allProductDTO.setStoreName(businessStore.getStoreName());
                //产品状态赋值
                allProductDTO.setProductState(product.getProductState()==0?"已上架":product.getProductState()==1?"已下架":"已删除");
                //保存数据
                allProductDTOS.add(allProductDTO);
            }
        }
        //分页对象转换
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setRecords(allProductDTOS);
        return pageInfo;
    }

    /**
     * 批量删除普通课程
     * @param storeId
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void removeProduct(Integer storeId) {
        Result<BusinessStoreDTO> businessStoreDTOResult = businessStoreClient.selByBusinessStoreId(storeId);
        //判断是否报错
        if (businessStoreDTOResult.getCode()!=200) throw new ProductException(businessStoreDTOResult.getCode(),businessStoreDTOResult.getMessage());
        //获取数据
        BusinessStoreDTO businessStoreDTO = businessStoreDTOResult.getData();
        //判断是否存在
        if (businessStoreDTO==null) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_STORE_ABSENT);
        //判断场馆状态是否异常
        if (businessStoreDTO.getStoreState()==BusinessState.STORE_STATE_DELETE) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_STORE_STATE_ERROR);
        //通过storeId查询普通产品
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("store_id",storeId);
        //索引排序
        wrapper.orderByAsc("product_id");
        List<Product> products = productMapper.selectList(wrapper);
        //判断是否存在
        if (products==null||products.size()<1) throw new ProductException(ProductExceptionCode.PRODUCT_EXCEPTION_CODE_NOT_EXIST);
        //遍历调用删除
        for (Product product : products) {
            //删除
            this.deleteProduct(product.getProductId());
        }
    }
}
